package v2;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@Slf4j
@Data
public class IndexTemplateV2 {

    private final static IKAnalyzer analyzer = new IKAnalyzer();

    private static File getIndexPath(Class clz) throws IOException {
        if (clz == null) {
            throw new IOException("no class found");
        }
        File file = new File("~/.index/" + clz.getSimpleName());
        if (!file.exists() && file.mkdirs()) {
            log.info("create dir({}) successfully", file.getAbsolutePath());
        }

        return file;
    }

    public static void main(String[] args) {
    }

    public int index(Iterable<Doc> docs, Class clz) throws IOException {
        if (docs == null) {
            return -1;
        }

        FSDirectory directory = FSDirectory.open(getIndexPath(clz));
        IndexWriter writer = getWriter(directory);

        try {
            int i = 0;
            for (Doc doc : docs) {
                writer.addDocument(doc.toDoc());
                i++;
            }
            return i;
        } catch (IOException e) {
            log.warn("document fail", e);
            return -1;
        } finally {
            writer.close(true);
            directory.close();
        }
    }

    public Set<Doc> find(Class objClass, String keyword) throws IOException, IllegalAccessException, InstantiationException {
        File path = getIndexPath(objClass);
        FSDirectory fsDirectory = FSDirectory.open(path);
        IndexReader indexReader = DirectoryReader.open(fsDirectory);
        IndexSearcher searcher = new IndexSearcher(indexReader);


        try {
            QueryParser parser2 = new QueryParser(Version.LUCENE_40, "title", analyzer);
            Query query = parser2.parse(keyword);

//        TermQuery query = new TermQuery(new Term("content", "你好"));
            query.setBoost(1.0f);
            TopDocs topDocs = searcher.search(query, 100);
            ScoreDoc[] scoreDocs = topDocs.scoreDocs;
            Set<Doc> set = new HashSet<>();
            for (ScoreDoc scoreDoc : scoreDocs) {
                Document doc = searcher.doc(scoreDoc.doc);
                set.add(((Doc) objClass.newInstance()).fromDoc(doc));
            }
            return set;
        } catch (ParseException | IOException e) {
            return Collections.emptySet();
        } finally {
            indexReader.close();
            fsDirectory.close();
        }
    }

    private IndexWriter getWriter(FSDirectory dir) throws IOException {
        if (dir == null) {
            throw new RuntimeException();
        }

        IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40, analyzer);

        return new IndexWriter(dir, config);
    }

}
